/* Copyright © Worklight Ltd. 2006-2011.  All rights reserved. */

package com.worklight.wlclient;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.cookie.Cookie;
import org.apache.http.cookie.CookieOrigin;
import org.apache.http.cookie.MalformedCookieException;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.BrowserCompatSpec;
import org.apache.http.impl.cookie.CookieSpecBase;
import org.apache.http.message.BasicHeader;

import com.worklight.wlclient.WLClientUtils;


public class WLCookieManager {
	private static Set<Cookie> cookies;
	
	/**
	 * Used to pass cookies from an outside source (WebView) to the cookie manager
	 * Overrides the Cookie Manager's cookie list
	 * @param cookiesString
	 */
	public static void setCookies(String cookiesString, String domain){
		if (cookiesString == null || cookiesString.length() == 0) {
			WLClientUtils.debug(String.format("setCookies() can't parse cookieString which is null or empty."));
			return;
		}
		if (domain == null || domain.length() == 0) {
			WLClientUtils.debug(String.format("setCookies() can't create cookies with a null or empty domain."));
			return;
		}

		HashSet<Cookie> cookieList = new HashSet<Cookie>();
		
		String cookies[] = cookiesString.split(";");
		for (int i = 0 ; i < cookies.length ;i++) {
			String[] keyValue = cookies[i].trim().split("=");
			if (keyValue.length == 2){
				BasicClientCookie cookie = new BasicClientCookie(keyValue[0].trim(), keyValue[1].trim());
				cookie.setDomain(domain);
				cookieList.add(cookie);
			} else {
				WLClientUtils.debug(String.format("setCookies() can't parse cookie %s.", cookies[i]));
			}
		}
		
		WLCookieManager.cookies = cookieList;
	}
	
	public static Set<Cookie> getCookies(){
		return cookies;
	}
	
	public static Header createCookieHeader(){
		Header header = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if ("JSESSIONID".equals(cookie.getName())) {
					header = new BasicHeader("X-WL-Cookie", cookie.getValue());
				}
			}
		}
		return header;
	}
	
	public static void handleResponseHeaders (Header[] headers, URI uri){
		if (WLCookieManager.cookies == null) {
			WLCookieManager.cookies = new HashSet<Cookie>();
		}

		CookieOrigin origin = new CookieOrigin(uri.getHost(), uri.getPort(), "/apps/services", false);
		CookieSpecBase cookieSpecBase = new BrowserCompatSpec();
		for (int i = 0 ; i < headers.length ; i++) {
			if (headers[i].getName().toLowerCase().equals("set-cookie")) {                    
				List<Cookie> theCookies;
				try {
					theCookies = cookieSpecBase.parse(headers[i], origin);
				} catch (MalformedCookieException e) {
					WLClientUtils.error("handleResponseHeaders Cannot parse cookies for header " + headers[i].getName(), e);
					throw new RuntimeException(e);
				}
				WLCookieManager.cookies.addAll(theCookies);
            } 
		}
	}

	public static void addCookies(WLRequest request) {
		if (cookies != null) {
			CookieSpecBase cookieSpecBase = new BrowserCompatSpec();
			List <Cookie> cookies = new ArrayList<Cookie>();
			cookies.addAll(WLCookieManager.getCookies());
			List <Header>cookieHeader = cookieSpecBase.formatCookies(cookies);	
			request.getPostRequest().setHeader(cookieHeader.get(0));
		}
	}
}

